package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpDelivery;
import cn.jekun.component.core.bean.gen.ErpMerchandiseType;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.ErpShopDelivery;
import cn.jekun.component.core.bean.gen.ErpShopImage;
import cn.jekun.component.core.bean.gen.ErpShoptype;
import cn.jekun.component.core.bean.gen.ErpSpeType;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsUserRole;
import cn.jekun.component.core.bean.gen.RsUserShop;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.TsClassifiedAccount;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.component.core.service.ScmService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpShopDeliveryService;
import cn.jekun.component.core.service.gen.ErpShopImageService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.core.service.gen.ErpShoptypeService;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.core.service.gen.RsUserRoleService;
import cn.jekun.component.core.service.gen.RsUserShopService;
import cn.jekun.component.core.service.gen.TsClassifiedAccountService;
import cn.jekun.component.core.validator.annotation.Identity;
import cn.jekun.component.shop.service.ThirdBusinessService;
import cn.jekun.shop.app.bean.ShopMessage;
import cn.jekun.shop.web.bean.Shops;

/**
 * 
 * @author twj
 *
 */
@Service(ShopService.BEAN_NAME)
public class ShopService1 extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.ShopService";

	@Resource(name=RsUserRoleService.BEAN_NAME)
	RsUserRoleService rsUserRoleService;
	
	@Resource(name=RsUserShopService.BEAN_NAME)
	RsUserShopService rsUserShopService;
	
	@Resource(name = AccountPayService.BEAN_NAME)
	private AccountPayService accountPayService;
	
	@Resource(name = TsClassifiedAccountService.BEAN_NAME)
	TsClassifiedAccountService tsClassifiedAccountService;
	
	
	@Resource(name = ScmService.BEAN_NAME)
	private ScmService scmService;
	
	@Resource(name = ErpShopDeliveryService.BEAN_NAME)
	private ErpShopDeliveryService erpShopDeliveryService;
	
	@Override
	public String getNamespace() {
		return "SHOP_SHOPMESSAGE";
	}
	@Resource(name = McMemberService.BEAN_NAME)
	McMemberService mcMemberService;
	@Resource(name =ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	@Resource(name = ErpShopImageService.BEAN_NAME)
	ErpShopImageService erpShopImageService;
	@Resource(name = ErpShoptypeService.BEAN_NAME)
	ErpShoptypeService erpShoptypeService;
	@Resource(name = ErpOrdersService.BEAN_NAME)
	ErpOrdersService erpOrdersService;
	@Resource(name = ShopOrderService.BEAN_NAME)
	ShopOrderService shopOrderService;
	/**
	 * 商家列表
	 * @param pageSize
	 * @param currentPage
	 * @param typeId
	 * @param lng
	 * @param lat
	 * @param cityId
	 * @param shopName
	 * @param speTypeId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject queryList(
			@Security
			String pageSize, 
			@Security
			String currentPage,
			@Security
			String typeId, 
			@Security
			String lng, 
			@Security
			String lat, 
			@Security
			String cityId,
			@Security
			String shopName,
			@Security
			String speTypeId,
			@Security
			String sort,
			@Security
			String shopId,
			@Security
			String distance,
			@Security
			String currentCityId) {
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List<Shops> resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(pageSize)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"页大小不能为空");
		}
		if (StringUtils.isBlank(currentPage)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"当前页不能为空");
		}
		/*if (StringUtils.isBlank(cityId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"当开通城市不能为空");
		}*/
		if (Constants.CITY_ALL.equals(cityId)) {//全国
			cityId = null;
		}
		page.setPageSize(Integer.parseInt(pageSize));
		page.setPageNumber(Integer.parseInt(currentPage));
		String order = "";
		formMap.put("typeId", typeId);
		formMap.put("cityId", cityId);
		formMap.put(ErpShop.COL_SHOP_TYPE_ID, typeId);
		formMap.put(ErpShop.COL_CITY_ID, cityId);
		formMap.put(ErpShop.COL_SHOP_NAME, shopName);
		formMap.put(ErpShop.COL_SHOP_ID, shopId);
		formMap.put(ErpSpeType.COL_SPE_TYPE_ID, speTypeId);
		formMap.put("currentCityId", currentCityId);
		//如果经纬度不为空则使用有带距离结果的算法
		if(StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lng)){
			//如果经纬度为空则查询结果不带距离算法
			//距离最近
			if("0".equals(sort)){
				order = "businessStatus asc, distance asc, seoweight desc nulls last";
			}
			//起送金额最少
			else if("1".equals(sort)){
				order = "businessStatus asc, minAmount asc, seoweight desc nulls last";
			}
			//默认
			else if("2".equals(sort)){
				order = "businessStatus asc, seoweight desc nulls last, distance asc";
			}
			//商家满意度
			else if("3".equals(sort)){
				order = "businessStatus asc, score desc nulls last , seoweight desc nulls last";
			}
			//TODO 销量高到低
			else if("4".equals(sort)){
				order = "";
			}
			//TODO 送货时间小到大
			else if("5".equals(sort)){
				order = "";
			}
			formMap.put("lng", lng);
			formMap.put("lat", lat);
			String distanceCondition = "";
			//当前城市 == 首页开通城市
			if(currentCityId.equals(cityId)){
				//只显示商家配送范围(range) >= 当前点到商家店的距离(distance)才显示出来
				distanceCondition = " and (sign(a.range-q.distance))>=0 ";
			}
			SqlUtis.prepareSql(formMap, 
					distanceCondition,
					StringUtils.isBlank(typeId)?"":" and a.shop_type_id in (select shop_type_id from erp_shoptype where shop_type_id = '"+typeId+"' or parent_id='"+typeId+"')",
					SqlUtis.getSQL(formMap, "e." + ErpSpeType.COL_SPE_TYPE_ID, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_CITY_ID, Types.VARCHAR,SqlUtis.EQ), 
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_ID, Types.VARCHAR,SqlUtis.EQ), 
//					SqlUtis.getSQL(formMap, "q."+"distance", Types.VARCHAR,SqlUtis.LE), 
					SqlUtis.getSQL(formMap, "a."+ErpShop.COL_SHOP_NAME,Types.VARCHAR,SqlUtis.LIKE),
					" and (a.BUSINESS_STATUS <> '4' and a.business_status <> '3' )",//结业
					SqlUtis.orderBy(order));
			resultList = this.list(formMap, page);
		}else{
			//如果经纬度为空则查询结果不带距离算法
			//起送金额最少
			if("1".equals(sort)){
				order = "businessStatus asc, minAmount asc, seoweight desc nulls last ";
			}
			//商家满意度
			else if("3".equals(sort)){
				order = "businessStatus asc, score desc nulls last, seoweight desc nulls last ";
			}
			//TODO 默认
			else if("2".equals(sort)){
				order = "businessStatus asc, seoweight desc nulls last";
			}
			//TODO 销量高到低
			else if("4".equals(sort)){
				order = "";
			}
			//TODO 送货时间小到大
			else if("5".equals(sort)){
				order = "businessStatus asc,ship_time asc, seoweight desc nulls last";
			}
			SqlUtis.prepareSql(formMap, 
					StringUtils.isBlank(typeId)?"":" and a.shop_type_id in (select shop_type_id from erp_shoptype where shop_type_id = '"+typeId+"' or parent_id='"+typeId+"')",
					SqlUtis.getSQL(formMap, "e." + ErpSpeType.COL_SPE_TYPE_ID, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_CITY_ID, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_SHOP_ID, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a."+ErpShop.COL_SHOP_NAME,Types.VARCHAR,SqlUtis.LIKE),
					" and ( a.BUSINESS_STATUS <> '4' and a.business_status <> '3')",//结业
					SqlUtis.orderBy(order));
			resultList = this.list(this.getStatementName("list2"), formMap, page);
		}
		jsonObject.put("shopList", resultList);
		jsonObject.put("totals", page.getTotalCount());
		jsonObject.put("pages", page.getPages());
		return executeRerutn(jsonObject);
	}
	/**
     * 首页推荐商家列表
     * @param lng  经度
     * @param lat  纬度
     * @param currentCityId 当前城市编码
     * @return
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject recommendShopList(String lng, String lat,
			String currentCityId) {
		
		if (Constants.CITY_ALL.equals(currentCityId)) {//全国
			currentCityId = null;
		}
		
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		page.setPageSize(5);
		page.setPageNumber(1);
		String order = "";
		List<Shops> resultList = new ArrayList<Shops>();
		Map formMap = new HashMap();
		formMap.put("currentCityId", currentCityId);
		formMap.put(ErpShop.COL_CITY_ID, currentCityId);
		formMap.put(ErpShop.COL_RECOMMENDED, "1");//推荐标识字段
		formMap.put(ErpShop.COL_BUSINESS_STATUS, "1");//营业中
		//如果经纬度不为空则使用有带距离结果的算法
		if(StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lng)){
			formMap.put("lng", lng);
			formMap.put("lat", lat);
			order = " seoweight desc nulls last, distance asc ";//按照距离由近到远排序
			SqlUtis.prepareSql(formMap, " and nvl2(decode(sign(a.range-q.distance),1,'1',0,'1',-1,'0'),decode(sign(a.range-q.distance),1,'1',0,'1',-1,'0'),0)='1' ",
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_CITY_ID, Types.VARCHAR,SqlUtis.EQ), 
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_RECOMMENDED, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_BUSINESS_STATUS, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.orderBy(order));
			resultList = this.list(formMap, page);
			
		}else{
		//如果不带经纬度
			order = " seoweight desc nulls last , a.create_time desc nulls last";//按创建时间排序
			SqlUtis.prepareSql(formMap, 
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_CITY_ID, Types.VARCHAR,SqlUtis.EQ), 
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_RECOMMENDED, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.getSQL(formMap, "a." + ErpShop.COL_BUSINESS_STATUS, Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.orderBy(order));
			resultList = this.list(this.getStatementName("list2"), formMap, page);
		}
		jsonObject.put("shopList", resultList);
		jsonObject.put("totals", page.getTotalCount());
		return executeRerutn(jsonObject);
	}
	/**
	 * 商家商品分类
	 * @param shopId 商家编码
	 * @param parentId 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public JSONObject shopGoodsType(
			@Security
			String parentId,
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject();
		List<ErpMerchandiseType> resultList = new ArrayList();
		Map formMap = new HashMap();
		ErpMerchandiseType merchandiseType = new ErpMerchandiseType();
		//如果shopId为空则查系统下所有默认商品类型并且该商品类型在商品表中有对应的商品
		if(StringUtils.isBlank(shopId) && StringUtils.isNotBlank(parentId)){
			formMap.put("parentId", parentId);
			resultList = this.list(this.getStatementName("queryMerchandiseTypelist2"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId(parentId);
			}
		}
		if(StringUtils.isBlank(shopId) && StringUtils.isBlank(parentId)){
			resultList = this.list(this.getStatementName("queryMerchandiseTypelist1"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId("");
			}
		}
		if(StringUtils.isBlank(parentId) && StringUtils.isNotBlank(shopId)){
			formMap.put("shopId", shopId);
			formMap.put("filter", "true");//过滤
			resultList = this.list(this.getStatementName("queryMerchandiseTypelistByShopId"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId("");
			}
		}
		if(StringUtils.isNotBlank(parentId) && StringUtils.isNotBlank(shopId)){
			formMap.put("shopId", shopId);
			formMap.put("parentId", parentId);
			formMap.put("filter", "true");//过滤
			resultList = this.list(this.getStatementName("queryMerchandiseTypelistByShopIdAndParentId"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId(parentId);
			}

		}
		
		//start 兼容旧版本
		if (StringUtils.isNotBlank(shopId) && resultList != null) {
			for (ErpMerchandiseType erpMerchandiseType : resultList) {
				erpMerchandiseType.setShopId(shopId);
			}
		}
		//end 兼容旧版本
		resultList.add(0,merchandiseType);
		jsonObject.put("goodsTypeList", resultList);
		return executeRerutn(jsonObject);
	}
	/**
	 * 商品管理-商家商品分类
	 * @param shopId 商家编码
	 * @param parentId 
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public JSONObject getShopGoodsType(
			@Security
			String parentId,
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject();
		List<ErpMerchandiseType> resultList = new ArrayList();
		Map formMap = new HashMap();
		ErpMerchandiseType merchandiseType = new ErpMerchandiseType();
		
		if(StringUtils.isBlank(parentId) && StringUtils.isNotBlank(shopId)){
			formMap.put("shopId", shopId);
			formMap.put("filter", "false");//表示获取全部的分类，不过滤
			resultList = this.list(this.getStatementName("queryMerchandiseTypelistByShopId"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId("");
			}
		}
		if(StringUtils.isNotBlank(parentId) && StringUtils.isNotBlank(shopId)){
			formMap.put("shopId", shopId);
			formMap.put("parentId", parentId);
			formMap.put("filter", "false");//表示获取全部的分类，不过滤
			resultList = this.list(this.getStatementName("queryMerchandiseTypelistByShopIdAndParentId"), formMap);
			if(resultList != null){
				merchandiseType.setMerchandiseTypeName("全部");
				merchandiseType.setMerchandiseTypeId(parentId);
			}

		}
		
		//start 兼容旧版本
		if (StringUtils.isNotBlank(shopId) && resultList != null) {
			for (ErpMerchandiseType erpMerchandiseType : resultList) {
				erpMerchandiseType.setShopId(shopId);
			}
		}
		//end 兼容旧版本
		resultList.add(0,merchandiseType);
		jsonObject.put("goodsTypeList", resultList);
		return executeRerutn(jsonObject);
	}
	/**
	 * 
	 * @param shopId
	 * @return
	 */
	public JSONObject queryAllMerchandiseTypelistByShopId(
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject();
		List<ErpMerchandiseType> resultList = new ArrayList();
		Map formMap = new HashMap();
		ErpMerchandiseType merchandiseType = new ErpMerchandiseType();
		formMap.put("shopId", shopId);
		resultList = this.list(this.getStatementName("queryAllMerchandiseTypelist"), formMap);
		
		List listData=new ArrayList();
		
		HashMap<String, Object> hashMap;
		
		List<String> pinyinList=new ArrayList<String>();
		for(int i=0;i<resultList.size();i++){
			 /* 
				if(!pinyinList.contains(resultList.get(i).getParentId())){
					pinyinList.add(resultList.get(i).getParentId());
					
					hashMap.put("parentId", resultList.get(i).getParentId());
					hashMap.put("merchandiseTypeId", resultList.get(i).getMerchandiseTypeId());
					hashMap.put("merchandiseTypeName", resultList.get(i).getMerchandiseTypeName());
					hashMap.put("childTypeList", getChildType(resultList.get(i).getParentId(),resultList));
					listData.add(hashMap);
				}else if(resultList.get(i).getParentId()==null){
					
					hashMap.put("parentId", resultList.get(i).getParentId());
					hashMap.put("merchandiseTypeId", resultList.get(i).getMerchandiseTypeId());
					hashMap.put("merchandiseTypeName", resultList.get(i).getMerchandiseTypeName());
					hashMap.put("childTypeList", getChildType(resultList.get(i).getParentId(),resultList));
					listData.add(hashMap);
				}*/
			if(resultList.get(i).getParentId()==null){
				hashMap=new HashMap<String, Object>();
				hashMap.put("parentId", resultList.get(i).getParentId());
				hashMap.put("merchandiseTypeId", resultList.get(i).getMerchandiseTypeId());
				hashMap.put("merchandiseTypeName", resultList.get(i).getMerchandiseTypeName());
				hashMap.put("childTypeList", getChildType(resultList.get(i).getMerchandiseTypeId(),resultList));
				listData.add(hashMap);
			}
			
		}
		
		
		jsonObject.put("goodsTypeList", listData);
		return executeRerutn(jsonObject);
	}
	
	public JSONArray getChildType(String pinyin,List<ErpMerchandiseType> list){
		
		JSONArray jsonArray=new JSONArray();
		
		
		for(int i=0;i<list.size();i++){
			
			if(pinyin!=null && pinyin.equals(list.get(i).getParentId())){
				JSONObject jsonObject=new JSONObject();
				jsonObject.put("parentId", list.get(i).getParentId());
				jsonObject.put("merchandiseTypeId", list.get(i).getMerchandiseTypeId());
				jsonObject.put("merchandiseTypeName", list.get(i).getMerchandiseTypeName());
				jsonArray.add(jsonObject);
			}
			
		}
		
		return jsonArray;
		
	}
	
	
	/**
	 * 关注商家
	 * @param userId
	 * @param shopId
	 * @param memberType 3:手机注册
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject concernShop(
			@Security
			String userId, 
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家编码不能为空");
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		formMap.put(McMember.COL_SHOP_ID, shopId);
		formMap.put(McMember.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, SqlUtis.getSQL(formMap, "a."
				+ McMember.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.getSQL(formMap, "a." + McMember.COL_USER_ID, Types.VARCHAR,
						SqlUtis.EQ));
		boolean flag = false;
		McMember tempMember = this.mcMemberService.one(formMap);
		if (tempMember != null) {
			if ("1".equals(tempMember.getConcern())) {
				throw new BusinessException(
						Constants.ERRORS.VALIDATE_ERROR_CODE, "您已关注此商家");
			} else {
				McMember saveMember = new McMember();
				saveMember.setConcern("1");
				saveMember.setMemberId(tempMember.getMemberId());
				this.mcMemberService.update(saveMember);
				flag = true;
			}
		} else {
			McMember member = new McMember();
			member.setUserId(userId);
			member.setShopId(shopId);
			member.setCredits(0.0);
			member.setConcern("1");
			member.setMemberTypeId(Constants.MC_MEMBER_TYPE.APP);
			Map tempMap = new HashMap();
			tempMap.put("mcMember", member);
			String returnId = this.mcMemberService.insert(tempMap).toString();
			if (returnId == null) {
				flag = false;
			} else {
				flag = true;
			}
		}
		if (!flag) {
			return executeRerutnFail(jsonObject);
		} else {
			return executeRerutn(jsonObject);
		}
	}
	/**
	 * 获取用户信息
	 * @param shopId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getShopIndo(
			@Security
			String shopId){
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
//		if (StringUtils.isBlank(shopId)) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"商家编码不能为空");
//		}
		if (StringUtils.isBlank(shopId)){
			jsonObject.put("shopName", "云便利商店");
			jsonObject.put("shopId", "");
			return executeRerutn(jsonObject);
		}else{
		formMap.put(ErpShop.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(formMap, 
				SqlUtis.getSQL(formMap, "a."+ ErpShop.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));
		ErpShop shop = this.erpShopService.one(formMap);
		if(shop == null){
			return executeRerutnFail(jsonObject);
		}
		String tempShopId = shop.getShopId();
		String shopName = shop.getShopName();
		jsonObject.put("shopId", tempShopId);
		jsonObject.put("shopName", shopName);
		return executeRerutn(jsonObject);
		}
	}
	/**
	 * 获取公共支付方式
	 * @param shopIds
	 * @return
	 */
	public JSONObject getPaymentByShopId(
			@Security
			String shopIds) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(shopIds)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		String shopids[] = shopIds.split(",");
		String sql = "";
		if(shopids.length<1){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		for(int i=0;i<shopids.length;i++){
			sql += "select a.payment_id,a.payment_name,a.sort from erp_payment a join erp_shop_payment b on (a.payment_id = b.payment_id) where( b.shop_id = '"+shopids[i]+"')";
			if(i==(shopids.length-1)){
				sql += "";
			}else{
			sql += " intersect  ";
			}
		}
		sql += " order by sort";
		List list = this.listBySql(sql);
		if(list.size()==0 || list == null){
			list = this.listBySql("select a.payment_id,a.payment_name from erp_payment a where a.payment_id='1'");
		}
		jsonObject.put("list", list);
		return executeRerutn(jsonObject);
	}
	
	public JSONObject getPaymentByShopIdWeb(
			@Security
			String cartIds){
		
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(cartIds)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"购物车代码不能为空");
		}
		String cartids[] = cartIds.split(",");
		String cartSql = "select a.shop_id from erp_cart a where a.cart_id='";
		for(int k=0;k<cartids.length;k++){
			cartSql += cartids[k]+"'";
			if(k==(cartids.length-1)){
				cartSql +=" ";
			}else{
				cartSql +=" or a.cart_id='";
			}
		}
		List<Map> tempList= this.listBySql(cartSql);
		String shopIds =""; 
		for(int q=0;q<tempList.size();q++){
			shopIds +=tempList.get(q).get("SHOP_ID").toString();
			if(q==tempList.size()-1){
				shopIds+="";
			}else{
				shopIds +=",";
			}
		}
		return this.getPaymentByShopId(shopIds);
	}
	/**
	 * 取消关注商家
	 * @param userId 用户编码
	 * @param shopId 商家编码
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject cancleConcernShop(
			@Security
			String userId, 
			@Security
			String shopId) {
		JSONObject jsonObject = new JSONObject();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家编码不能为空");
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		formMap.put(McMember.COL_SHOP_ID, shopId);
		formMap.put(McMember.COL_USER_ID, userId);
		formMap.put(McMember.COL_CONCERN, "1");
		SqlUtis.prepareSql(formMap, 
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a."+ McMember.COL_CONCERN, Types.VARCHAR, SqlUtis.EQ));
		McMember member = this.mcMemberService.one(formMap);
		if(member != null){
			McMember tempMember = new McMember();
			tempMember.setMemberId(member.getMemberId());
			tempMember.setConcern("0");
			this.mcMemberService.update(tempMember);
			return this.executeRerutn(jsonObject);
		}else{
			jsonObject.put(ErrorMsg.KEY_MESSAGE, "取消关注失败");
			return this.executeRerutnFail(jsonObject);
		}
	}
	
	/**
	 * 
	* @Title: getShopIntroduct
	* @Description: 获取商家的简介
	* @param @param shopId 用户代码
	* @param @return    设定文件
	* @return JSONObject    返回类型
	* @throws
	 */
    public JSONObject getShopIntroduct(@ErpShop.AnnoShopId String shopId){
    	JSONObject jsonObject = new JSONObject();
        if(StringUtils.isBlank(shopId) || shopId == null){
        	throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
        }
    	Map shopMap = new HashMap();
    	shopMap.put(ErpShop.COL_SHOP_ID,shopId);
    	SqlUtis.prepareSql(shopMap,SqlUtis.getSQL(shopMap, "a."+ErpShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
    	ErpShop erpShop = erpShopService.one(shopMap);
    	if(erpShop == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家不存在");
    	}
    	shopMap.clear();
    	shopMap.put(ErpShop.COL_SHOP_ID,shopId);
    	SqlUtis.prepareSql(shopMap,SqlUtis.getSQL(shopMap, "a."+ErpShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),SqlUtis.orderBy(ErpShopImage.COL_SORT + " DESC nulls last"));
        List<ErpShopImage> erpShopImgList = null;
        erpShopImgList = erpShopImageService.list(shopMap);
        String imageSize = "0";
        if(erpShopImgList == null){
        	 imageSize = "0";
        }else{
        	imageSize = erpShopImgList.size()+"";
        }
        jsonObject.put("shopName", erpShop.getShopName()==null?"":erpShop.getShopName()); //商家名称
        jsonObject.put("shopIntroduction", erpShop.getIntroduce()==null?"":erpShop.getIntroduce());//商家简介
        jsonObject.put("imageSize", imageSize); //商家拥有的简介图片数量
        jsonObject.put("shopImageList", erpShopImgList); //商家图片
    	return this.executeRerutn(jsonObject);
    }
    /**
     * 
    * @Title: switchBusinessStatus
    * @Description: 商家切换状态
    * @param @param shopId 用户代码
    * @param @param businessStatus（1：营业，2：休息）
    * @param @return    设定文件
    * @return JSONObject    返回类型
    * @throws
     */
    @Transactional
    public JSONObject switchBusinessStatus(@ErpShop.AnnoShopId String shopId,@ErpShop.AnnoBusinessStatus String businessStatus){
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId) || shopId == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空"); 
    	}
    	if(StringUtils.isBlank(businessStatus)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家切换的状态不为空"); 
    	}
    	ErpShop erpShop = this.erpShopService.one(shopId);
    	if (StringUtils.isBlank(erpShop.getBusinessStatus()) || "3".equals(erpShop.getBusinessStatus())) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"对不起，商家状态审核中，不能更改状态。");
		}
    	
    	ErpShop updateErpShop = new ErpShop();
    	updateErpShop.setShopId(shopId);
    	updateErpShop.setBusinessStatus(businessStatus);
    	erpShopService.update(updateErpShop);
    	
    	jsonObject.put("message", "商家切换状态成功");
        return this.executeRerutn(jsonObject);
    }
    
    /**
     * 
    * @Title: switchBusinessStatusType
    * @Description: 商家切换状态类型
    * @param shopId 用户代码
    * @param businessStatusType（1：营业，2：休息）
     */
    @Transactional
    public JSONObject switchBusinessStatusType(@ErpShop.AnnoShopId String shopId,@ErpShop.AnnoBusinessStatus String businessStatusType){
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId) || shopId == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空"); 
    	}
    	if(StringUtils.isBlank(businessStatusType)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家切换的状态类型不为空"); 
    	}
    	ErpShop updateErpShop = new ErpShop();
    	updateErpShop.setShopId(shopId);
    	updateErpShop.setBusinessStatusType(businessStatusType);
    	erpShopService.update(updateErpShop);
        return this.executeRerutn(jsonObject);
    }

    /**
     * 
    * @Title: getShopIndoBusinesStatus
    * @Description: 商家初始化
    * @param @param shopId 用户代码
    * @param @return    设定文件
    * @return JSONObject    返回类型
    * @throws
     */
    public JSONObject getShopIndoBusinesStatus(@ErpShop.AnnoShopId String shopId){
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId) || shopId == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	Map shopMap = new HashMap();
    	shopMap.put(ErpShop.COL_SHOP_ID,shopId);
        SqlUtis.prepareSql(shopMap, SqlUtis.getSQL(shopMap, "a."+ErpShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
        ErpShop shop = this.erpShopService.one(shopMap);
        if(shop == null){
        	throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家不存在");
        }
        jsonObject.put("shop", shop);
    	return this.executeRerutn(jsonObject);
    }
    /**
     *  根据shopId查找商家基本信息
     *  @param shopId 商家代码
     *  @return
     *
     */
    public JSONObject getShopInfoByShopId(@ErpShop.AnnoShopId String shopId){
    	logger.info("===================ShopService getShopInfoByShopId begin=============================");
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	Map map = new HashMap();
    	map.put("shop_id", shopId);
    	SqlUtis.prepareSql(map, SqlUtis.getSQL(map, "a.shop_id", Types.VARCHAR, SqlUtis.EQ));
        ShopMessage shopMessage = this.one("SHOP_SHOPMESSAGE.getShopInfo", map);
        if(shopMessage == null){
        	jsonObject.put("erpShop", "");
        }else{
        	//判断配送方式是否为自提
        	if("2".equals(shopMessage.getDeliveryId())){
        		shopMessage.setIsZiti("1");
        	}else{
        		shopMessage.setIsZiti("0");
        	}
            jsonObject.put("erpShop", shopMessage);
        }
        logger.info("===================ShopService getShopInfoByShopId end=============================");
        return this.executeRerutn(jsonObject);
    }
    

     
    /**
     * 獲取商家類型列表
     *  @return
     *
     */
    public JSONObject  getShopType(){
    	logger.info("=========================ShopService getShopType begin========================");
    	JSONObject jsonObject = new JSONObject();
    	Map map= new HashMap();
    	List<ErpShoptype> erpShoptypes = this.erpShoptypeService.list(map);
    	if(erpShoptypes == null){
    		jsonObject.put("erpShoptypes", "");
    	}else{
    	    jsonObject.put("erpShopTypeList", erpShoptypes);
        }
    	logger.info("=========================ShopService getShopType begin========================");
    	return this.executeRerutn(jsonObject);
   }
    
    
    
    
    /**
     *  修改商家的基本信息
     *  @param shopId 商家代码
     *  @param logoUrl 商家logo路径
     *  @param shopName 商家简称
     *  @param comName  商家全名
     *  @param shopTypeId 商家类型代码
     *  @param phone 联系电话
     *  @param mobile 手机号码
     *  @param contact 联系人
     *  @param businessHourse 营业时间
     *  @param minAmount 最小起送金额
     *  @param range 配送范围
     *  @param address 地址
     *  @param street  详细地址
     *  @param provinceId 省代码
     *  @param cityId   市代码
     *  @param regionId 区域代码
     *  @param longItude 经度
     *  @param latiItude 纬度
     *  @return
     *
     */
    @Transactional
    public JSONObject updateShopMessage(@ErpShop.AnnoShopId String shopId,@ErpShop.AnnoLogoUrl String logoUrl,@ErpShop.AnnoShopName String shopName,
            @ErpShop.AnnoComName String comName,@ErpShop.AnnoShopTypeId String shopTypeId,@ErpShop.AnnoPhone String phone,@ErpShop.AnnoMobile String mobile,
            @ErpShop.AnnoContact String contact,@ErpShop.AnnoBusinessHours String businessHours,@ErpShop.AnnoMinAmount String minAmount,
            String range,@ErpShop.AnnoAddress String address,@ErpShop.AnnoStreet String street,@ErpShop.AnnoProvinceId String provinceId,@ErpShop.AnnoCityId String cityId,
            @ErpShop.AnnoRegionId String regionId,@ErpShop.AnnoLongitude String longItude,@ErpShop.AnnoLatitude String latItude,String isZiti,String deliveryAmount){
    	
    	logger.info("=========================ShopService getShopType begin========================");
    	JSONObject jsonObject = new JSONObject();
        if(shopId == null){
        	throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
        }
        
        ErpShop erpShop = new ErpShop();
        erpShop.setShopId(shopId);
        erpShop.setLogoUrl(logoUrl);
        erpShop.setShopName(shopName);
        erpShop.setComName(comName);
        erpShop.setShopTypeId(shopTypeId);
        erpShop.setPhone(phone);
        erpShop.setMobile(mobile);
        erpShop.setContact(contact);
        erpShop.setBusinessHours(businessHours);
        erpShop.setMinAmount(StringUtils.isBlank(minAmount)?null:Double.parseDouble(minAmount));
        erpShop.setRange(StringUtils.isBlank(range)?null:Integer.parseInt(range));        
    	erpShop.setAddress(address);
    	erpShop.setStreet(street);
    	erpShop.setProvinceId(provinceId);
    	erpShop.setCityId(cityId);
    	erpShop.setRegionId(regionId);
    	erpShop.setLongitude(StringUtils.isBlank(longItude)?null:Double.parseDouble(longItude));
    	erpShop.setLatitude(StringUtils.isBlank(latItude)?null:Double.parseDouble(latItude));
    	
    	erpShop.setDeliveryAmount(StringUtils.isBlank(deliveryAmount)?null:Double.parseDouble(deliveryAmount));
    	
    	try{
    	//更新商家的基本信息
    	this.erpShopService.update(erpShop);
    	
    	Map deliveryMap = new HashMap();
    	deliveryMap.put(ErpShopDelivery.COL_SHOP_ID, shopId);
    	deliveryMap.put(ErpShopDelivery.COL_DELIVERY_ID, "2");
    	SqlUtis.prepareSql(deliveryMap,
    			SqlUtis.getSQL(deliveryMap, "a."+ErpShopDelivery.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),
    			SqlUtis.getSQL(deliveryMap, "a."+ErpShopDelivery.COL_DELIVERY_ID,Types.VARCHAR,SqlUtis.EQ));
    	ErpShopDelivery tempDelivery = this.erpShopDeliveryService.one(deliveryMap);
    	//如果是自提
    	if("1".equals(isZiti)){
    		//开通自提配送方式
    		if(tempDelivery==null){
    			ErpShopDelivery shopDelivery = new ErpShopDelivery();
    			shopDelivery.setShopId(shopId);
    			shopDelivery.setDeliveryId("2");
    			this.erpShopDeliveryService.insert(shopDelivery);
    		}
    	}else if("0".equals(isZiti)){
    		//关闭自提配送方式
    		if(tempDelivery!=null){
    			this.erpShopDeliveryService.delete(tempDelivery.getShopDeliveryId());
    		}
    	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	logger.info("=========================ShopService getShopType begin========================");
    	return this.executeRerutn(jsonObject);
    }
    
    /**
     *  获取商家图片
     *  @param shopId
     *  @return
     *
     */
    public JSONObject getShopPics(@ErpShop.AnnoShopId String shopId){
    	
    	logger.info("=========================ShopService getShopPics begin========================");
    	
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	
    	Map shopImgMap = new HashMap();
    	shopImgMap.put(ErpShopImage.COL_SHOP_ID,shopId);
    	SqlUtis.prepareSql(shopImgMap,SqlUtis.getSQL(shopImgMap, "a."+ErpShopImage.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),SqlUtis.orderBy(ErpShopImage.COL_SORT + " DESC nulls last"));
    	List<ErpShopImage> erpShopImgList = null;
    	
    	try{
            erpShopImgList = erpShopImageService.list(shopImgMap);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	
        String imageSize = "0";
        if(erpShopImgList == null){
        	 imageSize = "0";
        }else{
        	 imageSize = erpShopImgList.size()+"";
        }
    	
    	jsonObject.put("erpShopImgList", erpShopImgList);
    	
    	logger.info("========================ShopService getShopPics end============================");;
        return this.executeRerutn(jsonObject);
    }
    
    /**
     *  商家上传相片
     *  @param shopId 商家代码
     *  @param userId 用户代码
     *  @param shopPicUrl 图片路径
     *  @return
     *
     */
    @Transactional
    public JSONObject addShopPic(String shopId,String userId,String shopPicUrl){
    	logger.info("=========================ShopService addShopPic begin========================");
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	if(StringUtils.isBlank(userId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不为空");
    	}
    	if(StringUtils.isBlank(shopPicUrl)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"上传图片路径不为空");
    	}
    	
    	Map shopImgMap = new HashMap();
    	shopImgMap.put(ErpShopImage.COL_SHOP_ID,shopId);
    	SqlUtis.prepareSql(shopImgMap,SqlUtis.getSQL(shopImgMap, "a."+ErpShopImage.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),SqlUtis.orderBy(ErpShopImage.COL_SORT + " DESC nulls last"));
    	List<ErpShopImage> erpShopImgList = null;
    	String tempImageId ="";
    	//获取商家相册列表
    	erpShopImgList = erpShopImageService.list(shopImgMap);
    	int tempSize = erpShopImgList.size();
//        String[] picUrls = shopPicUrl.split(",");
        
//        for(int i=0,length = picUrls.length>=(10-tempSize)?10-tempSize:picUrls.length;i<length;i++){
    	//查看该商家是否已存在相册，并得到最近一张相片的排序号
    	int sort;
    	if(erpShopImgList == null || erpShopImgList.size() == 0){
    		sort = 1;
    	}else{
    		if(tempSize > 10){
    			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家相册已满10张");
    		}
    		sort =  erpShopImgList.get(0).getSort()==null?tempSize+1:erpShopImgList.get(0).getSort()+1;
    	}
    	//设置值
    	ErpShopImage erpShopImage = new ErpShopImage();
    	erpShopImage.setImageUrl(shopPicUrl);
    	erpShopImage.setShopId(shopId);
    	erpShopImage.setCreateName(userId);
        erpShopImage.setSort(sort);    	
    	try{
    		tempImageId = this.erpShopImageService.insert(erpShopImage).toString();
    		jsonObject.put("shopPicId", tempImageId);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
//        }
    	logger.info("=========================ShopService addShopPic end========================");
    	return this.executeRerutn(jsonObject);
    }
    
    /**
     *  刪除圖片
     *  @param shopPicId
     *  @return
     *
     */
    @Transactional
    public JSONObject delShopPic(@ErpShopImage.AnnoImageId String shopPicId){
    	logger.info("=========================ShopService delShopPic begin========================");
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopPicId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家相册图片Id代码不为空");
    	}
    	try{
    	    this.erpShopImageService.delete(shopPicId);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	logger.info("=========================ShopService delShopPic end========================");
    	return this.executeRerutn(jsonObject);
    }
    
    /**
     *  修改商家简介
     *  @param shopId 商家代码
     *  @param introduction 商家简介
     *  @return
     *
     */
    @Transactional
    public JSONObject modifyShopIntroduction(@ErpShop.AnnoShopId String shopId,@ErpShop.AnnoIntroduce String introduction){
    	logger.info("=========================ShopService modifyShopIntroduction begin========================");
    	JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	
    	ErpShop erpShop = new ErpShop();
    	erpShop.setShopId(shopId);
    	erpShop.setIntroduce(introduction);
    	
    	try{
    	
    		this.erpShopService.update(erpShop);
    	
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	logger.info("=========================ShopService modifyShopIntroduction end========================");
    	return this.executeRerutn(jsonObject);
    }
    /**
     * 展示商家公告和商家经营状态
     * @param shopId
     * @return
     */
	public JSONObject showShopNoticeAndBusinessStatus(String shopId) {
		JSONObject jsonObject = new JSONObject();
    	if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	ErpShop shop = this.erpShopService.one(shopId);
    	if(shop == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"找不到商家任何信息");
    	}
    	if(shop != null){
    		if(StringUtils.isNotBlank(shop.getNotice())){
    			jsonObject.put("notice", shop.getNotice());
    		}else{
//    			jsonObject.put("notice", "暂无公告");
    			jsonObject.put("notice", "");
    		}
    		if(StringUtils.isNotBlank(shop.getBusinessStatus())){
    			if("1".equals(shop.getBusinessStatus())){
    				jsonObject.put("businessStatus", shop.getBusinessStatus());
    				jsonObject.put("memo", "");
    			}else if("2".equals(shop.getBusinessStatus())){
    				jsonObject.put("businessStatus", shop.getBusinessStatus());
    				jsonObject.put("memo", "休息中");
//    				jsonObject.put("memo", "");
    			}else{
    				jsonObject.put("businessStatus", shop.getBusinessStatus());
    				jsonObject.put("memo", "此商家处于审核中，暂不接受订单");
//    				jsonObject.put("memo", "");
    			}
    		}
    		jsonObject.put("shopName", shop.getShopName());
    	}
    	return this.executeRerutn(jsonObject);
	}
	/**
	 * 店铺详情
	 * @param shopId 商家编码
	 * @param userId 用户编码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject queryShopMessage(String shopId, String userId) {
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}
    	ErpShop erpShop = this.erpShopService.one(shopId);
    	if(erpShop == null){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"找不到商家任何信息");
    	}
    	if(StringUtils.isBlank(erpShop.getNotice())){
    		erpShop.setNotice("");
    	}
    	Double tempScore = erpShop.getScore();
	    if(tempScore == null){
	    	tempScore = 0.0;
	    }else if(tempScore > 0 && tempScore < 1){
	    	tempScore = 0.5;
	    }else if(tempScore > 1 && tempScore < 2){
	    	tempScore = 1.5;
	    }else if(tempScore > 2 && tempScore <3){
	    	tempScore = 2.5;
	    }else if(tempScore > 3 && tempScore <4){
			tempScore = 3.5;
		}else if(tempScore > 4 && tempScore <5){
			tempScore = 4.5;
		}
	    erpShop.setScore(tempScore);
	    String tempIntroduct = erpShop.getIntroduce();
	    if(tempIntroduct !=null && tempIntroduct.length() > 200){
	    	tempIntroduct = tempIntroduct.substring(0, 200);
	        erpShop.setIntroduce(tempIntroduct);
	    }
		jsonObject.put("shop", erpShop == null ? "[]" : erpShop);
		// 商家特色
		String spe = "";
		List<Map> list = this
				.listBySql("select listagg(c.spe_type_id,',') within GROUP (order by b.shop_id) spe from erp_shop_spe b join erp_spe_type c on (b.spe_type_id = c.spe_type_id) where b.shop_id='"
						+ shopId + "' group by b.shop_id");
		if (list == null || list.size() == 0) {
			spe = "";
		} else {
			spe = list.get(0).get("SPE").toString();
		}
		jsonObject.put("speId", spe);
		// 商家支持的支付方式
		String payments = "";
		List<Map> paymentList = this
				.listBySql("select listagg(a.payment_id, ',') within GROUP(order by a.shop_id) payments from erp_shop_payment a join erp_payment b on (a.payment_id = b.payment_id) where a.shop_id ='"
						+ shopId + "' group by a.shop_id");
		if (paymentList == null || paymentList.size() == 0) {
			payments = "";
		} else {
			payments = paymentList.get(0).get("PAYMENTS").toString();
		}
		jsonObject.put("payments", payments);
		boolean scoreAbleFlag = false;
		//用户是否在商家下单过，用于评分权限判断
		if(userId != null && !userId.equals("")){
			Map scoreAbleMap = new HashMap();
			scoreAbleMap.put("user_id", userId);
			scoreAbleMap.put("shop_id", shopId);
			scoreAbleMap.put("order_status_id", "3");
	        SqlUtis.prepareSql(scoreAbleMap,SqlUtis.getSQL(scoreAbleMap,"a.shop_id",Types.VARCHAR,SqlUtis.EQ),
	        		SqlUtis.getSQL(scoreAbleMap,"a.user_id",Types.VARCHAR,SqlUtis.EQ),
	        		SqlUtis.getSQL(scoreAbleMap, "a.order_status_id",Types.VARCHAR,SqlUtis.EQ));
	        scoreAbleFlag = this.erpOrdersService.exists(scoreAbleMap);
		}
		jsonObject.put("scoreAbleFlag", scoreAbleFlag);
		//获取商家相册
    	Map shopImgMap = new HashMap();
    	shopImgMap.put(ErpShopImage.COL_SHOP_ID,shopId);
    	SqlUtis.prepareSql(shopImgMap,SqlUtis.getSQL(shopImgMap, "a."+ErpShopImage.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),SqlUtis.orderBy(ErpShopImage.COL_SORT + " DESC nulls last"));
    	List<ErpShopImage> erpShopImgList = null;
    	try{
            erpShopImgList = erpShopImageService.list(shopImgMap);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        String imageSize = "0";
        if(erpShopImgList == null){
        	 imageSize = "0";
        }else{
        	 imageSize = erpShopImgList.size()+"";
        }
    	jsonObject.put("imageSize", imageSize);
    	jsonObject.put("erpShopImgList", erpShopImgList);
    	//获取商家的各种订单状态的数量
    		Map map = new HashMap();
			map.put(ErpShop.COL_PARENT_SHOP_ID, shopId);
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map, "a."+ErpShop.COL_PARENT_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
			//判断shopId是不是拥有分店
			List tempList = new ArrayList();
			if(this.erpShopService.exists(map)){
				tempList = this.shopOrderService.getOrderTypeAndTotalsShops(shopId);
			}else{
				
				tempList = this.shopOrderService.getOrderTypeAndTotals(shopId);
			}
    	jsonObject.put("orderTypeTotalList", tempList);
    	
    	//是否已经开通在线支付服务
    	if ("3".equals(erpShop.getBusinessStatus())) {//审核中
			Map existsMap = new HashMap();
			existsMap.put("shopId", shopId);//商家代码
			existsMap.put("merchandiseId", Constants.ERP_SHOP_FUWU.ONLIE_PAYMENT);//商品代码
			String orderId = this.one(this.getStatementName("getFuwuToPay"), existsMap );
			boolean toPayFuwu = StringUtils.isNotBlank(orderId);
			jsonObject.put("toPayFuwu", toPayFuwu?"1":"0");
			jsonObject.put("toPayOrderId",orderId);
		}else {
			jsonObject.put("toPayFuwu", "0");
			jsonObject.put("toPayOrderId","");
		}
    	return this.executeRerutn(jsonObject);
	}
	
	
	/**
	 * 开店获取商家分类
	 * @return
	 */
	public JSONObject getOpenShopType(String parentId) {
		JSONObject jsonObject = new JSONObject();
		
		Map map = new HashMap();
		map.put(ErpShoptype.COL_SHOP_TYPE_ID, "2,1,50,4,3,5");
		map.put(ErpShoptype.COL_PARENT_ID, parentId);
		
		if(StringUtils.isBlank(parentId)){
			
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map,
					ErpShoptype.COL_SHOP_TYPE_ID),
					SqlUtis.orderBy(ErpShoptype.COL_SORT));
		}else{
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map,
					ErpShoptype.COL_PARENT_ID,Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.orderBy(ErpShoptype.COL_SORT));
		}
	
		List<ErpShoptype> types = erpShoptypeService.list(map );
		jsonObject.put("types", JSONArray.fromObject(types));
		
		return this.executeRerutn(jsonObject);
	}
	/**
	 * 开店保存商家信息
	 * @param shopName
	 * @param identityNo
	 * @param identityImage1
	 * @param identityImage2
	 * @param identityImage3
	 * @param provinceId
	 * @param cityId
	 * @param regionId
	 * @param address
	 * @param longitude
	 * @param latitude
	 * @param phone
	 * @param certificate1
	 * @param certificate2
	 * @param certificate3
	 * @param certificate4
	 * @param certificate5
	 * @return
	 */
	@Transactional
	public JSONObject openShop(
			@NotBlank(message="商家名称不能为空")
			@ErpShop.AnnoShopName
			String shopName, 
			
			@NotBlank(message="身份证号码不能为空")
			@Identity
			@ErpShop.AnnoIdentityNo
			String identityNo, 
			
			@NotBlank(message="身份证图片1不能为空")
			@ErpShop.AnnoIdentityaUrl
			String identityImage1, 
			
			@NotBlank(message="身份证图片2不能为空")
			@ErpShop.AnnoIdentitybUrl
			String identityImage2, 
			
			@NotBlank(message="身份证图片3不能为空")
			@ErpShop.AnnoIdentitycUrl
			String identityImage3, 
			
			@NotBlank(message="省份代码不能为空")
			@ErpShop.AnnoProvinceId
			String provinceId, 
			
			@NotBlank(message="城市代码不能为空")
			@ErpShop.AnnoCityId
			String cityId, 
			
			@NotBlank(message="区域代码不能为空")
			@ErpShop.AnnoRegionId
			String regionId, 
			
			@NotBlank(message="详细地址不能为空")
			@ErpShop.AnnoAddress
			String address, 
			
			@ErpShop.AnnoStreet
			String street, 
			
			@NotBlank(message="经度不能为空")
			@ErpShop.AnnoLongitude
			String longitude, 
			
			@NotBlank(message="纬度不能为空")
			@ErpShop.AnnoLatitude
			String latitude, 
			
			@ErpShop.AnnoPhone
			String phone, 
			
			@ErpShop.AnnoMobile
			String mobile, 
			
			@NotBlank(message="商家支付密码不能为空")
			@Security
			String psw, 
			
			@ErpShop.AnnoCertificateaUrl
			String certificate1, 
			
			@ErpShop.AnnoCertificatebUrl
			String certificate2, 
			
			@ErpShop.AnnoCertificatecUrl
			String certificate3, 
			
			@ErpShop.AnnoCertificatedUrl
			String certificate4, 
			
			@ErpShop.AnnoCertificateeUrl
			String certificate5,
			
			@Security
			String createUserId,
			
			@NotBlank(message="商家类型不能为空")
			@ErpShop.AnnoShopTypeId
			String shopTypeId,
			
			String email,
			
			String range
			) {
		JSONObject jsonObject = new JSONObject();
		
		RsUser user = new RsUser();
		user.setUserId(createUserId);
		if(StringUtils.isNotBlank(email)){
			user.setEmail(email);
		}else{
			user.setEmail("");
		}
		user.setEmail(email);
		//将开店邮箱保存到开店用户信息中
		this.rsUserService.update(user);
		
		ErpShop erpShop = new ErpShop();
		erpShop.setShopName(shopName);
		erpShop.setIdentityNo(identityNo);
		erpShop.setIdentityaUrl(identityImage1);
		erpShop.setIdentitybUrl(identityImage2);
		erpShop.setIdentitycUrl(identityImage3);
		erpShop.setShopTypeId(shopTypeId);
		erpShop.setProvinceId(provinceId);
		erpShop.setCityId(cityId);
		erpShop.setRegionId(regionId);
		erpShop.setAddress(address);
		erpShop.setStreet(street);
		erpShop.setLongitude(Double.parseDouble(longitude));
		erpShop.setLatitude(Double.parseDouble(latitude));
		erpShop.setPhone(phone);
		erpShop.setMobile(mobile);
		erpShop.setMsgMobile(mobile);
		erpShop.setCertificateaUrl(certificate1);
		erpShop.setCertificatebUrl(certificate2);
		erpShop.setCertificatecUrl(certificate3);
		erpShop.setCertificatedUrl(certificate4);
		erpShop.setCertificateeUrl(certificate5);
		erpShop.setCreateName(createUserId);
		erpShop.setBusinessStatusType("1");
		erpShop.setBusinessStatus("3");//审核中
		erpShop.setRecommended("0");//推荐
		try{
			erpShop.setRange(Integer.parseInt(range));//配送范围
		}catch(Exception e){
			erpShop.setRange(0);
		}
		
		this.erpShopService.insert(erpShop);//保存商家
		
		//增加账户
		JSONObject json = accountPayService.create(erpShop.getShopId(), Constants.TS_ACCOUNT_OWNER_TYPE.SHOP, psw, Constants.TS_ACCOUNT_SIGN_TYPE.SIGN_TYPE_00, "0","开店创建账户");
		String accountId = json.getString("accountId");
		TsClassifiedAccount tsClassifiedDay=new TsClassifiedAccount();
		tsClassifiedDay.setAccountId(accountId);
		tsClassifiedDay.setAmount(0d);
		tsClassifiedDay.setChannelId("00");//默认终端
		tsClassifiedDay.setIsDeposit(Constants.TS_ACCOUNT_ISDEPOSIT.DEPOSIT_00);
		tsClassifiedDay.setStatusId(Constants.TS_ACCOUNT_STATUS.STATUS_00);
		tsClassifiedDay.setTypeId(Constants.TS_CLASSIFIED_ACCOUNT_TYPE.CLASSIFIED_00);
		tsClassifiedDay.setCreateName("system");
		tsClassifiedAccountService.insert(tsClassifiedDay);
		
		//把用户加到店员
		RsUserShop rsUserShop = new RsUserShop();
		rsUserShop.setCreateName(createUserId);
		rsUserShop.setMemo("开店增加店员");
		rsUserShop.setShopId(erpShop.getShopId());
		rsUserShop.setUserId(createUserId);
		this.rsUserShopService.insert(rsUserShop);
		
		//默认添加商家角色
		RsUserRole role=new RsUserRole();
		role.setRoleId("SJ");
		role.setUserId(createUserId);
		this.rsUserRoleService.insert(role);
		

		//提交审核发送短信
    	
    	smsService.sendSMS(mobile, "尊敬的"+shopName+"！您的开店申请已提交，请稍后留意审核结果短信！");
		
    	//同步开店用户到scm系统
    	RsUser tempUser = this.rsUserService.one(createUserId);
    	boolean flag = this.scmService.synDataToScm(tempUser);
    	if(!flag){
    		log.info("#######用户数据同步失败#########");
    	}else{
    		log.info("#######用户数据同步成功#########");
    	}
		
		//购买服务
		jsonObject = ThirdBusinessService.createShopFuWuService().addOrder(erpShop.getShopId(), createUserId, Constants.ERP_SHOP_FUWU.ONLIE_PAYMENT, Constants.ERP_ORDER_TYPE.APP, Constants.ERP_PAYMENT.PAYMENT_ONLINE);
		if (ErrorMsg.CALL_OK.equals(jsonObject.optString(ErrorMsg.KEY_CODE) )) {
			String orderId = jsonObject.getString("orderId");//订单代码
			ErpOrders erpOrders = this.erpOrdersService.one(orderId);
			
			if (Constants.ERP_ORDER_STATUS.ORDER.equals(erpOrders.getOrderStatusId())) {//不需要支付
				ThirdBusinessService.createShopFuWuService().afterPay(erpOrders, "system");
				jsonObject.put("toPay", "0");//1需要支付0不需要支付
			}else{
				jsonObject.put("toPay", "1");//1需要支付0不需要支付
			}
			
			jsonObject.put("shopId", erpShop.getShopId());
			jsonObject.put("shopName", erpShop.getShopName());
			return this.executeRerutn(jsonObject);
		}else{
			return executeRerutnFail(jsonObject);
		}
		
	}
	/**
	 * 获取商家配送方式
	 * @param shopId
	 * @return
	 */
	public JSONObject getShopDeliveryType(String shopId) {
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
    		throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不为空");
    	}else{
    		//兼容android1.1.6
    		if(shopId.indexOf(",")>=0){
    			
    			shopId=shopId.split(",")[0];
    		}
    	}
		String sql = "select a.delivery_id as deliveryId,a.delivery_name deliveryName from erp_delivery a join erp_shop_delivery b on (a.delivery_id = b.delivery_id) where b.shop_id = '"+shopId+"'";
		List list = this.listBySql(sql);
		list.add(0,"{\"DELIVERYNAME\"=\"商家配送\", \"DELIVERYID\"=\"1\"}");
		jsonObject.put("list", list);
		return executeRerutn(jsonObject);
	}
	

    
}
